/* openlayer api 工具类 minxin引入 */
import appApi from '@/common/appApi'
module.exports = {
	data() {
		return {
			geoServerUrl: appApi.geoServerUrl[appApi.server],
			map: null, //地图对象
			layerType: {
				tdt_img: {
					iurl: 'https://t{0-7}.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=', //影像底图
					// iurl: 'http://t{0-7}.tianditu.com/img_w/wmts?tk=',
					webKey: 'e9c7767838d54199022216dbedd62738',
					layerName: 'img',
					name: '影像',
					funcName: 'getTDTLayer',
					layerIdentify: -1
				},
				tdt_cva: {
					iurl: 'http://t{0-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=',
					// iurl: 'http://t{0-7}.tianditu.com/cva_w/wmts?tk=', //地图标注
					webKey: 'e9c7767838d54199022216dbedd62738',
					layerName: 'cva',
					name: '地图标注',
					funcName: 'getTDTLayer'
				},
				tdt_ibo: {
					iurl: 'http://t{0-7}.tianditu.com/DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=',
					// iurl: 'http://t{0-7}.tianditu.com/ibo_w/wmts?tk=', //
					webKey: 'e9c7767838d54199022216dbedd62738',
					layerName: 'ibo',
					name: '境界',
					funcName: 'getTDTLayer'
				},
				tdt_vec: {
					iurl: 'http://t{0-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=',
					// iurl: 'http://t{0-7}.tianditu.com/vec_w/wmts?tk=', //
					webKey: 'e9c7767838d54199022216dbedd62738',
					layerName: 'vec',
					name: '矢量底图',
					funcName: 'getTDTLayer',
					layerIdentify: -1
				}
			},
			mapOptions: {
				target: 'olmap', //绑定id
				currentZoom: 4, //初始化时的缩放大小
				maxZoom: 20,
				minZoom: 4,
				layers: ['tdt_img', 'tdt_ibo', 'tdt_cva'], //地图类型
				center: [0, 0],
				control: {
					attribution: false, //去掉logo
					zoom: false, //缩放按钮
					rotate: true, //旋转按钮 
					rotateoptions: {
						label: ''
					},
					zoomoptions: {},
					attributionOptions: {}
				}
			},
			style: {
				// 我的位置样式
				myLocation: (style) => {
					return new ol.style.Style({
						image: new ol.style.Icon({
							anchor: [0.5, 0.5], //锚点 0-1
							opacity: 1,
							src: style.imageUrl || 'static/icon_my_location.png' //图标的URL
						})
					})
				},
				//区域分组图标样式
				areaGroup: (style) => {
					return new ol.style.Style({
						image: new ol.style.Icon({
							anchor: [0.5, 0.5], //锚点 0-1
							opacity: 1,
							src: style.imageUrl || 'static/icon_my_location.png', //图标的URL
							imgSize: [36, 36]
						}),
						text: new ol.style.Text({
							offsetY: 24, //y轴偏移 //可以根据图标大小设置
							textAlign: 'center', //位置
							textBaseline: 'middle', //基准线
							font: '14px', //文字样式
							text: style.label, //文本内容
							fill: new ol.style.Fill({ //文本填充样式（即文字颜色)
								color: '#fc341e'
							}),
							stroke: new ol.style.Stroke({
								color: '#ffffff',
								width: 1
							})
						})
					})
				},
				//巡查标签
				inpectFlag: (style) => {
					return new ol.style.Style({
						image: new ol.style.Icon({
							anchor: [0.5, 1], //锚点 0-1
							opacity: 1,
							src: style.imageUrl || 'static/red_flag.png', //图标的URL
						}),
						text: new ol.style.Text({
							offsetY: -20, //y轴偏移 //可以根据图标大小设置
							textAlign: 'center', //位置
							textBaseline: 'middle', //基准线
							font: '14px', //文字样式
							text: style.label, //文本内容
							fill: new ol.style.Fill({ //文本填充样式（即文字颜色)
								color: '#ffffff'
							}),
						})
					})
				},
				/* 巡园标签 聚合图标 */
				inpectFlagCluster: (style) => {
					return new ol.style.Style({
						image: new ol.style.Icon({
							anchor: [0.5, 1], //锚点 0-1
							opacity: 1,
							src: style.imageUrl || 'static/red_flag.png', //图标的URL
						}),
						text: new ol.style.Text({
							offsetY: -20, //y轴偏移 //可以根据图标大小设置
							textAlign: 'center', //位置
							textBaseline: 'middle', //基准线
							font: '14px', //文字样式
							text: style.size > 1 ? style.label : style.text, //文本内容
							fill: new ol.style.Fill({ //文本填充样式（即文字颜色)
								color: '#ffffff'
							}),
						})
					})
				},
				//聚合点样式 
				male: (style) => {
					return new ol.style.Style({
						image: new ol.style.Icon({
							anchor: [0.5, 1], //锚点 0-1
							opacity: 1,
							src: 'static/icon_map_marker.png', //图标的URL
							imgSize: [40, 40]
						}),
						text: new ol.style.Text({
							offsetY: -24, //y轴偏移 //可以根据图标大小设置
							textAlign: 'center', //位置
							textBaseline: 'middle', //基准线
							font: '13px', //文字样式
							text: style.label, //文本内容
							fill: new ol.style.Fill({ //文本填充样式（即文字颜色)
								color: '#ffffff'
							}),
						})
					})
				},
				//选中的多边形样式
				slectedPolygon: (style) => {
					return new ol.style.Style({
						fill: new ol.style.Fill({
							color: 'rgba(255, 255, 255, 0.4)'
						}),
						stroke: new ol.style.Stroke({
							color: '#ffcc33',
							width: 2
						}),
						image: new ol.style.Circle({
							radius: 8,
							fill: new ol.style.Fill({
								color: '#ff0000'
							})
						})
					})
				}
			},
			locationlayer: null, //我的定位点所在图层
			resolutions: [20, 200, 2000] //图层分辨率阈值
		}
	},
	methods: {
		//刷新
		refreshMapView() {
			let view = this.map.getView();
			console.log(view.getResolution());
			view.setResolution(view.getResolution() + Math.random() * 0.00000001);
			console.log(view.getResolution());
		},
		/* 地图配置项 */
		initMap(options) {

			if (this.map != null) {
				return;
			}
			let opt = this.mapOptions
			if (options) {
				opt = Object.assign(this.mapOptions, options)
			};
			this.map = new ol.Map({
				target: opt.target,
				controls: this.getControls(opt.control), // 地图控制按钮
				view: this.getView(opt)
			});
			//添加图层来源
			if (opt.layers && opt.layers.length > 0) {
				// //默认底图层
				// this.map.addLayer(new ol.layer.Tile({
				// 	source: new ol.source.OSM()
				// }))
				let ls = this.getSourcelayer(opt.layers);
				// 	console.log(ls);
				ls.forEach(e => {
					this.map.addLayer(e)
				});
			} else {
				//默认底图层
				this.map.addLayer(new ol.layer.Tile({
					source: new ol.source.OSM()
				}))
			}

		},
		/* View 视图管理器，主要用来管理地图视图，分辨率或旋转，中心、投影、分辨率、缩放级别等 */
		getView(opt) {
			let projection = new ol.proj.Projection({
				code: 'EPSG:3857',
				units: 'm',
				axisOrientation: 'neu'
			});
			let view = new ol.View({
				center: ol.proj.transform(opt.center, 'EPSG:4326', 'EPSG:3857'),
				zoom: opt.currentZoom,
				minZoom: opt.minZoom,
				maxZoom: opt.maxZoom,
				projection: projection,
				// extent: [-20037508.34, -20037508.34, 20037508.34, 20037508.34]
			});
			return view
		},
		/* 	用于设置地图上的ui组件。 */
		getControls(controlOpt) {
			let control = ol.control.defaults({
				attribution: controlOpt.attribution,
				zoom: controlOpt.zoom,
				rotate: controlOpt.rotate,
				attributionOptions: controlOpt.attributionOptions,
				rotateOptions: controlOpt.rotateoptions,
				zoomOptions: controlOpt.zoomoptions
			})
			return control
		},
		/* 解析对应地图图层来源 数组  */
		getSourcelayer(layers) {
			let result = []
			if (layers && layers.length > 0) {
				let layer = null
				let option = null;
				layers.forEach(elem => {
					option = this.layerType[elem]; //根据键名获取对应的地图配置项
					layer = this[option.funcName](option);
					result.push(layer)
				})
			}
			return result
		},
		/* 加载天地图图层 */
		getTDTLayer(option) {
			let {
				iurl,
				webKey,
				layerName,
				name,
				layerIdentify
			} = option;
			// console.log(iurl + webKey);
			let projection = ol.proj.get('EPSG:3857');
			let layer = new ol.layer.Tile({
				name: name,
				layerIdentify: layerIdentify || '', //定义的图层标识 
				source: new ol.source.XYZ({
					url: iurl + webKey,
					// layer: layerName,
					projection: projection,
					maxZoom: 18
					// style: 'default',
					// crossOrigin: 'anonymous',
				})
			});
			return layer
		},
		/* 获取地块图层 */
		getGeoImageLayer(wmsUrl, layersName) {
			console.log(wmsUrl);
			let url = wmsUrl;
			let layer = new ol.layer.Image({
				title: "地块图层",
				source: new ol.source.ImageWMS({
					ratio: 1,
					title: '地块图层',
					url: url,
					params: {
						'VERSION': '1.1.1',
						"LAYERS": layersName,
						'FORMAT': 'image/png',
						"exceptions": 'application/vnd.ogc.se_inimage',
					}
				})
			});
			// console.log(layer);
			return layer;
		},
		addLayer(lay) {
			if (this.map) {
				this.map.addLayer(lay);
			}
		},
		removeLayer(lay) {
			if (this.map) {
				this.map.removeLayer(lay);
			}
		},
		/* 设置中心点 */
		setCenter(center) {
			console.log('setCenter', center);
			if (this.map) {
				return this.map.getView().setCenter(center);
			}
		},
		getMapCenter() {
			//获取当前中点坐标
			return this.map.getView().getCenter();
		},
		//获取地图当前层级
		getZoom() {
			if (this.map) {
				return this.map.getView().getZoom();
			} else {
				return null;
			}
		},
		//设置当前放大层级
		setZoom(zoom) {
			if (this.map && typeof zoom === 'number') {
				this.map.getView().setZoom(zoom);
			}
		},
		//设置最小放大层级
		getMinZoom() {
			if (this.map) {
				return this.map.getView().getMinZoom();
			} else {
				return null;
			}
		},
		//设置最大放大层级
		getMaxZoom() {
			if (this.map) {
				return this.map.getView().getMaxZoom();
			} else {
				return null;
			}
		},
		//更新地图Div尺寸
		updateSize() {
			if (this.map) {
				this.map.updateSize();
			}
		},
		//获取地图当前层级
		getZoom() {
			if (this.map) {
				return this.map.getView().getZoom();
			} else {
				return null;
			}
		},
		/* 判断是否可以放大 */
		zoomPlusEnable() {
			return this.getZoom() < this.getMaxZoom()
		},
		/* 判断是否可以缩小 */
		zoomReduceEnable() {
			return this.getMinZoom() < this.getZoom()
		},
		/* 注册单击事件 */
		registerSingleClick(func) {
			//事件
			if (typeof func === 'function') {
				this.map.on('singleclick', func);
			}
		},
		/* 注册移动事件 */
		registerMoveEnd(func) {
			//事件
			if (typeof func === 'function') {
				this.map.on('moveend', func);
			}
		},
		//获取当前绘制图层的中心点坐标
		getCenterPoint(coordinates) {
			var centerPoint = [];
			var lng = 0.0;
			var lat = 0.0;
			var ps = [];
			for (var tmp in coordinates) {
				var _t = coordinates[tmp];
				//反过来
				var m_center = [_t[0], _t[1]]; //地图中心点-xy坐标
				//经纬度转至经纬度
				m_center = ol.proj.transform(m_center, 'EPSG:3857', 'EPSG:4326');
				ps.push(m_center);
			}
			if (ps.length > 0) {
				for (var tmp in ps) {
					lng = lng + ps[tmp][0];
					lat = lat + ps[tmp][1];
				}
				lng = lng / ps.length;
				lat = lat / ps.length;
				centerPoint.push(lng);
				centerPoint.push(lat);
			}

			return centerPoint;
		},
		/* 添加标记点 */
		getMarker(list) {
			//格式, coordinate经度，y纬度，name图标下方显示的文字，imgurl图标图片路径
			//若经纬度不是3857则需要转换
			// let coordinate = ol.proj.transform(m.coordinate, 'EPSG:4326', 'EPSG:3857');
			let features = list.map(elem => {
				let f = new ol.Feature({
					geometry: new ol.geom.Point(elem.coordinate),
					type: elem.type || 'default',
					...elem
				});
				//设置id方便查询
				if (elem.id != null && elem.id != undefined) {
					f.setId(elem.id);
				}
				f.setStyle(this.style[elem.type](elem));
				return f
			});
			// feature.setStyle(this.style[m.type](m));
			let vectorLayer = new ol.layer.Vector({
				source: new ol.source.Vector({
					crossOrigin: 'anonymous',
					features: features
				}),
				//设置图标样式
				// style: (feature) => {
				// 	return this.style[feature.get('type')](feature)
				// }
			});

			return vectorLayer
		},
		getClusterMarker(list) {
			let features = list.map(elem => {
				let f = new ol.Feature({
					geometry: new ol.geom.Point(elem.coordinate),
					type: elem.type || 'default',
					...elem //绑定一些额外参数 方便业务处理 
				});
				//设置id方便查询
				if (elem.id != null && elem.id != undefined) {
					f.setId(elem.id);
				}

				return f
			});
			let source = new ol.source.Vector({
				features: features
			});
			let cluster = new ol.source.Cluster({ // 创建聚合标注对象
				distance: 40, // 设置聚合标注的距离
				source: source
			});
			let vectorLayer = new ol.layer.Vector({
				source: cluster,
				//设置图标样式
				style: (feature) => {
					var size = feature.get('features').length; //当前聚合数量
					var type = feature.get('features')[0].get('type');
					// console.log(size, feature.get('features')[0].get('type'));
					if (size > 1) {
						return this.style[type]({
							label: size + '',
							size: size
						})
					} else {
						return this.style[type]({
							label: size + '', //文本内容 
							size: size, //聚合数量
							imageUrl: feature.get('features')[0].get('imageUrl'), //图片
							text: feature.get('features')[0].get('label') //文本内容 
						})
					}

				}
			});
			return vectorLayer
		},
		/* 多边形 */
		getPolygonFeature(coords, type) {
			let features = coords.map(p => {
				// console.log(p);
				let f = new ol.Feature({
					geometry: new ol.geom.Polygon([p.coordinates])
				});
				//设置id方便查询
				if (p.id != null && p.id != undefined) {
					f.setId(p.id);
				}
				f.setStyle(this.style[type](p));
				return f
			});
			return features
		},
		/* 创建多边形展示的图层 */
		getPolygonlayer(features) {
			//创建同图层
			console.log(features);
			//实例化一个矢量图层Vector作为绘制层
			let source = new ol.source.Vector({
				crossOrigin: 'anonymous',
				features: features
			});
			let layer = new ol.layer.Vector({
				source: source
			});
			return layer
		},
		/* 影像 遥感图层 */
		getWmsLayer(gridsetName, gridNames, layerName, resolutions, baseUrl) {
			//var gridsetName = 'EPSG:4326';
			//var gridNames = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10', 'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19', 'EPSG:4326:20', 'EPSG:4326:21'];
			//var baseUrl = 'http://192.168.0.79:6080/geoserver/gwc/service/wmts';
			//var layerName = 'YMKJ:L19';
			//var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4, 8.58306884765625E-5, 4.291534423828125E-5, 2.1457672119140625E-5, 1.0728836059570312E-5, 5.364418029785156E-6, 2.682209014892578E-6, 1.341104507446289E-6, 6.705522537231445E-7, 3.3527612686157227E-7];
			//3857偏差很大，建议使用4326
			let url = baseUrl;
			let style = '';
			let version = '1.0.0';
			let format = 'image/png';
			let infoFormat = 'text/html';
			let projectionOpt = null;
			let tileGridOpt = null;
			if (gridsetName.indexOf('3857') >= 0) {
				projectionOpt = {
					code: gridsetName,
					units: 'm',
					axisOrientation: 'neu'
				};
				tileGridOpt = {
					tileSize: [256, 256],
					extent: [-2.003750834E7, -2.003750834E7, 2.003750834E7, 2.003750834E7],
					origin: [-2.003750834E7, 2.003750834E7],
					resolutions: resolutions,
					matrixIds: gridNames
				}
			} else if (gridsetName.indexOf('4326') >= 0) {
				projectionOpt = {
					code: gridsetName,
					units: 'degrees',
					axisOrientation: 'neu'
				};
				tileGridOpt = {
					tileSize: [256, 256],
					extent: [-180.0, -90.0, 180.0, 90.0],
					origin: [-180.0, 90.0],
					resolutions: resolutions,
					matrixIds: gridNames
				}
			}

			let source = new ol.source.WMTS({
				url: url,
				layer: layerName,
				matrixSet: gridsetName,
				format: format,
				projection: new ol.proj.Projection(projectionOpt),
				tileGrid: new ol.tilegrid.WMTS(tileGridOpt),
				style: style,
				wrapX: true,
				version: version
			});
			let layer = new ol.layer.Tile({
				source: source
			});
			return layer;
		}
	}
}
